package com.japhet.stripesdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.stripe.model.*;
import com.stripe.net.Webhook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;


/**
 *  stripe 回调controller
 *  需要注意避坑
 *
 *  这里我用的是 checkout api进行拉起支付的，所以stripe官网也只会回调checkou.xxx ，不会走payment_intent.xxx
 *  也就是event事件回调通知
 *
 *
 *
 *                 PaymentIntent intent = (PaymentIntent) event
 *                     .getDataObjectDeserializer()
 *                     .getObject()
 *                     .get();
 *                 case "payment_intent.created"://创建订单 这里事件就是图二选着的事件
 *                     System.out.println("---------------nnnnnnnnnnnnnnnnnnnnnn---------------");
 *                     break;
 *                 case "payment_intent.canceled"://取消订单
 *                     System.out.println("---------------canceledcanceledcanceledcanceledcanceledcanceled---------------");
 *                     break;
 *                 case "payment_intent.succeeded"://支付成功
 *                     if(intent.getStatus().equals("succeeded")) {
 *                         System.out.println("---------------success---------------");
 *                         Map<String,String> metaData = intent.getMetadata();//自定义传入的参数
 *                         String orderId = metaData.get("orderId");//自定义订单号
 *                         System.out.println(orderId);
 *                         *//*********** 根据订单号从数据库中找到订单，并将状态置为成功 *********//*
 *                     }
 *                     break;
 *                 case "payment_intent.payment_failed"://支付失败
 *                     System.out.println("Failed: " + intent.getId());
 *                     System.out.println("---------------payment_failed---------------");
 *                     break;
 *
 */




@Controller
public class StripeBackController {
    @ResponseBody
    @RequestMapping(value = {"/api/pay/stripe/stripe_events"}, method = RequestMethod.POST)
    public void stripe_events(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------进入回调了------");
        try {
            String endpointSecret = "whsec_vInPmYjyKxxxxxxxxxxxxxxxxx";//webhook秘钥签名
            InputStream inputStream = request.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*4];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();
            String payload = new String(bytes, "UTF-8");
            String sigHeader = request.getHeader("Stripe-Signature");
            Event event = Webhook.constructEvent(payload, sigHeader, endpointSecret);//验签，并获取事件

            PaymentIntent intent = (PaymentIntent) event
                .getDataObjectDeserializer()
                .getObject()
                .get();

            switch(event.getType()) {
                case "checkout.session.completed"://支付完成
                    System.out.println("---------------success2222222---------------");
                    String s = event.getDataObjectDeserializer().getObject().get().toJson();
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    JSONObject jsonObject2 = (JSONObject)jsonObject.get("metadata");
                    String orderId = jsonObject2.getString("orderId");
                    System.out.println("订单号为："+orderId);
                    System.out.println("根据订单号从数据库中找到订单，并将状态置为支付成功状态");
                    break;
                case "checkout.session.expired"://过期
                    System.out.println("---------------checkout.session.expired---------------");
                    break;
                case "payment_intent.created"://创建订单 这里事件就是图二选着的事件
                     System.out.println("---------------nnnnnnnnnnnnnnnnnnnnnn---------------");
                     break;
                case "payment_intent.canceled"://取消订单
                     System.out.println("---------------canceledcanceledcanceledcanceledcanceledcanceled---------------");
                     break;
                case "payment_intent.succeeded"://支付成功
                     if(intent.getStatus().equals("succeeded")) {
                         System.out.println("---------------success---------------");
                         Map<String,String> metaData = intent.getMetadata();//自定义传入的参数
                         String orderId2 = metaData.get("orderId");//自定义订单号
                         System.out.println("订单号为："+orderId2);
                         System.out.println("根据订单号从数据库中找到订单，并将状态置为支付成功状态");
                         //*********** 根据订单号从数据库中找到订单，并将状态置为成功 *********//*
                     }
                     break;
                 case "payment_intent.payment_failed"://支付失败
                     System.out.println("Failed: " + intent.getId());
                     System.out.println("---------------payment_failed---------------");
                     break;

                default:
                    break;
            }
        } catch (Exception e) {
            System.out.println("stripe异步通知（webhook事件）"+e);
        }
    }
}